package com.cl.ks.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cl.ks.utils.CommonResult;
import com.cl.ks.utils.DbUtil;
import com.cl.mvc.service.BaseService;

import com.cl.ks.entity.SqlTemplate;
import com.cl.ks.repository.SqlTemplateRepository;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.cl.ks.constant.QTableConstant.qSqlTemplate;

@Slf4j
@Service
public class SqlTemplateService extends BaseService<SqlTemplate> {
    @Autowired
    JPAQueryFactory queryFactory;
    @Autowired
    DbUtil dbUtil;

    private final SqlTemplateServiceUtil sqlTemplateServiceUtil;

    protected SqlTemplateService(SqlTemplateRepository SqlTemplateRepository, SqlTemplateServiceUtil sqlTemplateServiceUtil) {
        super(SqlTemplateRepository);
        this.sqlTemplateServiceUtil = sqlTemplateServiceUtil;
        sqlTemplateServiceUtil.init();
    }

    public CommonResult list(String code, String area) {

        String createTempTableSql = "CREATE TEMPORARY TABLE fl_clue_temp AS " +
                "SELECT * FROM fl_clue WHERE JSON_UNQUOTE(JSON_EXTRACT(content, '$.district')) LIKE '%" + area + "%';";
        dbUtil.executeSQL(null, createTempTableSql);

        String sql = queryFactory.select(qSqlTemplate.templateContent).from(qSqlTemplate).where(qSqlTemplate.code.eq(code)).fetchOne();
        List<Map<String, Object>> list = dbUtil.fetchSQL(null, sql);

        String dropTempTableSql = "DROP TEMPORARY TABLE IF EXISTS fl_clue_temp";
        dbUtil.executeSQL(null, dropTempTableSql);
        return CommonResult.success(list);
    }

    public CommonResult listAll(String area) {
        return CommonResult.success(sqlTemplateServiceUtil.getResCache(area));
    }
}
